package com.smartfast4j.backend.modules.sys.service.impl;

import com.smartfast4j.backend.common.util.ShiroUtils;
import com.smartfast4j.backend.modules.sys.entity.SysUser;
import com.smartfast4j.backend.modules.sys.mapper.SysUserMapper;
import com.smartfast4j.backend.modules.sys.security.shiro.SysUserRealm;
import com.smartfast4j.backend.modules.sys.service.SysUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.smartfast4j.backend.modules.sys.vo.SysMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author 孤傲苍狼
 * @since 2017-09-05
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRealm userRealm;

    @Override
    public List<String> queryAllPerms(Long userId) {
        return baseMapper.queryAllPerms(userId);
    }

    @Override
    public int updatePassword(Long sysLoginUserId, String password, String newPassword) {
        //原密码
        password = ShiroUtils.sha256(password, ShiroUtils.getLoginSysUser().getSalt());
        //新密码
        newPassword = ShiroUtils.sha256(newPassword, ShiroUtils.getLoginSysUser().getSalt());
        SysUser sysUser = selectById(sysLoginUserId);
        if(!sysUser.getPassword().equals(password)){
            return 0;
        }else{
            sysUser.setPassword(newPassword);
        }
        //修改用户密码
        boolean updateResult = updateById(sysUser);
        if(updateResult){
            //修改密码成功后要清除登录认证缓存信息，否则用户无法使用新密码进行登录
            userRealm.clearCachedAuthenticationInfo();
            return 1;
        }
        return 0;
    }
}
